#include "MenuScreen.h"
#include "MAHeaders.h"
#include "../std.h"
#include "../Utilities/trim.h"
#include "../Widgets/Colours.h"
#include "../Widgets/UIBuilder.h"

MenuScreen::MenuScreen(){
	mLayout = new Layout(0, 0, APPCONTROLLER->getScreenWidth(), APPCONTROLLER->getScreenHeight(), NULL, 1, 3);
	softKeys = createSoftKeyBar(HEIGHTBAR, getStringNotIterative(L_SELECT), getStringNotIterative(L_CANCEL));

	Layout* lblBound = new Layout(0,0, APPCONTROLLER->getScreenWidth(), APPCONTROLLER->getScreenHeight()- softKeys->getHeight() - HEIGHTITEM * 3 - VERTICALPADDING * 2,mLayout, 1, 1);
	lblBound->setDrawBackground(false);

	mMenu = new ListBox(0 , 0, APPCONTROLLER->getScreenWidth(), HEIGHTITEM * 3 + VERTICALPADDING * 2, mLayout, ListBox::LBO_VERTICAL, ListBox::LBA_LINEAR, true);
	mMenu->setPaddingTop(VERTICALPADDING * 2);
	mMenu->setPaddingLeft(VERTICALPADDING * 2);
	mMenu->setPaddingRight(VERTICALPADDING * 2);
	mMenu->setBackgroundColor(BLACK);
	mMenu->setDrawBackground(true);

	mLayout->add(softKeys);

	this->setMain(mLayout);
}

MenuScreen::~MenuScreen(){
	delete mLayout;
}

void MenuScreen::keyPressEvent(int keyCode, int nativeCode){
	switch(keyCode)
	{
		case MAK_SOFTLEFT:
		case MAK_FIRE:
			listener->menuIndex(mMenu->getSelectedIndex());
			break;
		case MAK_UP:
			mMenu->selectPreviousItem();
			break;
		case MAK_DOWN:
			mMenu->selectNextItem();
			break;
		case MAK_SOFTRIGHT:
			listener->menuIndex(-1);
			break;
	}
}

void MenuScreen::pointerReleaseEvent(MAPoint2d point){

}

void MenuScreen::pointerPressEvent(MAPoint2d point){
	Point p;
	p.set(point.x, point.y);

	if (softKeys->contains(p)){
		if(softKeys->getChildren()[0]->contains(p)) keyPressEvent(MAK_SOFTLEFT, 0);
		else if (softKeys->getChildren()[1]->contains(p)) keyPressEvent(MAK_SOFTRIGHT, 0);
	}
}

void MenuScreen::setListener(MenuListener* input){
	listener = input;
}

void MenuScreen::addMenuItem(String& input)
{
	Label* l = new Label(0, 0, APPCONTROLLER->getScreenWidth() - VERTICALPADDING * 4, HEIGHTITEM, NULL);
	l->setPaddingLeft(VERTICALPADDING * 2);
	l->setCaption(input);
	l->setMultiLine(false);
	l->setHorizontalAlignment(Label::HA_LEFT);
	l->setVerticalAlignment(Label::VA_CENTER);
	l->setSkin(APPCONTROLLER->getSkin("default"));
	mMenu->add(l);
	mMenu->setSelectedIndex(0);
}

void MenuScreen::clearMenuItem()
{
	if (mMenu->getChildren()[0]!= NULL){
		mMenu->setSelectedIndex(0);
	}
	mMenu->clear();
}
